from django.shortcuts import render
from rest_framework.viewsets import  GenericViewSet
from rest_framework.mixins import  CreateModelMixin
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from . import models,ser
from rest_framework.response import Response
from rest_framework.views import APIView
# Create your views here.
class PayView(GenericViewSet, CreateModelMixin):
    authentication_classes = [JSONWebTokenAuthentication,]
    permission_classes = [IsAuthenticated,]
    queryset = models.Order.objects.all()
    serializer_class = ser.OrderSerializer

    #因为要给序列化类传入request。所以这里需要重写create 方法
    def create(self, request, *args, **kwargs):
        serializer= self.get_serializer(data=request.data, context={'request':request})
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return Response(serializer.context.get('pay_url'))

#前端及支付宝异步回调接口
class SuccessView(APIView):
    '''
    前端拿到支付宝回调的数据后会在 url拼接参数返回给给后端
    通过前端返回的订单号，可以去数据库订单表中拿到记录，查看其订单状态字段，用来判断该订单状态是否已经修改
    '''
    #前端异步回调接口
    def get(self, request,*args, **kwargs):
        out_trade_no = request.query_params.get('out_trade_no')
        order = models.Order.objects.filter(out_trade_no=out_trade_no).first()
        if order.order_status == 1:
            return Response(True)
        else:
            return Response(False)


    #支付宝异步回调接口
    def post(self, request, *args, **kwargs):
        '''
        支付宝回调接口
        '''
        from luffy.libs.aipay import alipay
        from luffy.utils.logger import log
        # data = request.data #支付宝回调的数据， data格式：urlencoded
        print('---->',request.data)
        data = request.data.dict() #urlencoded转为字典格式
        out_trade_no = data.get('out_trade_no', None)
        gmt_payment = data.get('gmt_paymet', None) #支付时间
        signature = data.get('sign') #签名
        #验证签名
        success = alipay.verify(data, signature)
        #通过验证签名，可以判断订单是否正常
        if success and data['trade_status'] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
            #修改订单状态
            models.Order.objects.filter(out_trade_no=out_trade_no).uptate(order_status=1, pay_time=gmt_payment)
            log.info('%s 订单支付成功'%out_trade_no)
            return Response('success')
        else:
            log.info('%s订单有问题'%out_trade_no)
            return Response('error')
